package com.petshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.petshop.controller.CartItemsController;
import com.petshop.controller.UsersController;
import com.petshop.dto.OrderDTO;
import com.petshop.mapper.*;
import com.petshop.pojo.Address;
import com.petshop.pojo.CartItems;
import com.petshop.pojo.Orders;
import com.petshop.pojo.Users;
import com.petshop.service.OrdersService;
import com.petshop.utils.JwtHelper;
import com.petshop.utils.Result;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static com.petshop.utils.Constant.*;

/**
 * @author 20289
 * @description 针对表【orders(存储用户订单信息)】的数据库操作Service实现
 * @createDate 2025-03-08 22:35:56
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartItemsController cartItemsController;
    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private UsersController usersController;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CartItemsMapper cartItemsMapper;
    @Autowired
    private ProductsMapper productsMapper;

    /**
     * 增加一条订单
     *
     * @param orderDTO
     * @param token
     * @return
     */
    @Override
    public Result insertOrder(OrderDTO orderDTO, String token) {
        //获取当前用户
        Users user = usersController.getUserInfo(token);
        //比较余额和总价
        if (user.getAccount().subtract(orderDTO.getBalance()).compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("余额不足！请及时充值");
        }
        //查询出购物车选中的商品信息
        List<CartItems> cartItems = cartItemsController.getCartItems(orderDTO.getCartIds());
        //将商品信息给订单变量
        for (CartItems cartItem : cartItems) {
            Orders order = getOrders(orderDTO, cartItem, user.getUserId());
            //添加到数据库里
            int i = ordersMapper.insert(order);
            if (i > 0) {
                //修改库存
                productsMapper.updateReduceStock(cartItem.getProductId(), cartItem.getQuantity());
            }
        }
        //修改余额
        usersMapper.reduceBalance(user.getUserId(), orderDTO.getBalance());
        //删除购物车里提交订单的商品
        cartItemsMapper.deleteBatchIds(orderDTO.getCartIds());
        return Result.ok("下单成功！");
    }

    private @NotNull Orders getOrders(OrderDTO orderDTO, CartItems cartItem, int userId) {
        Orders order = new Orders();
        //加入商品信息到订单里
        order.setUserId(userId);
        order.setName(cartItem.getProductName());
        order.setPrice(cartItem.getProductPrice());
        order.setProductId(cartItem.getProductId());
        order.setBuyNumber(cartItem.getQuantity());
        order.setOrderImage(cartItem.getCartImage());
        order.setGoodId(null);
        order.setTotalAmount(cartItem.getProductPrice().multiply(new BigDecimal(cartItem.getQuantity())));
        order.setStatus(ORDER_STATUS_WAITSEND);
        //加入地址信息
        order.setAddress(orderDTO.getAddress().getAddress());
        order.setReceiver(orderDTO.getAddress().getReceiver());
        order.setPhoneNumber(orderDTO.getAddress().getPhone());
        //加入创建修改时间信息
        order.setCreatedAt(new Date());
        order.setUpdatedAt(new Date());
        return order;
    }

    /**
     * 删除一条订单
     *
     * @param orderId
     * @return
     */
    @Override
    public Result deleteOrder(Integer orderId) {
        boolean bool = removeById(orderId);
        if (bool) {
            return Result.ok("删除订单成功！");
        }
        return Result.error("订单删除失败");
    }

    /**
     * 修改订单信息
     *
     * @param orders
     * @return
     */
    @Override
    public Result updateOrder(Orders orders) {
        orders.setUpdatedAt(new Date());
        int i = ordersMapper.updateById(orders);
        if (i > 0) {
            return Result.ok("修改成功");
        }
        return Result.error("修改失败！请重试");
    }

    /**
     * 查询所有订单信息
     *
     * @return
     */
    @Override
    public Result queryAllOrder(String token) {
        Integer userId = jwtHelper.getUserId(token).intValue();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId);
        List<Orders> orders = ordersMapper.selectList(queryWrapper);
        return Result.ok(orders);
    }

    /**
     * 根据订单状态查询订单信息
     *
     * @return
     */
    @Override
    public Result queryOrderByStatus(String status) {
        LambdaQueryWrapper<Orders> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getStatus, status);
        List<Orders> orders = ordersMapper.selectList(lambdaQueryWrapper);
        return Result.ok(orders);
    }

    /**
     * 根据商品名模糊查询订单
     *
     * @param name
     * @return
     */
    @Override
    public Result queryOrderByName(String name) {
        LambdaQueryWrapper<Orders> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Orders::getName, name);
        List<Orders> orders = ordersMapper.selectList(lambdaQueryWrapper);
        if (orders != null) {
            return Result.ok(orders);
        }
        return Result.error("您还没有相关订单");
    }

    /**
     *
     */
    /**
     * 确认收货后修改订单状态
     *
     * @param orderId
     * @return
     */
    @Override
    public Result updateOrderStatus(Integer orderId) {
//        Orders orders = queryById(orderId);
        Orders orders = getById(orderId);
        String status = orders.getStatus();
        if (status.equals(ORDER_STATUS_WAITRECEIVE)) {
            int i = ordersMapper.updateStatus(orderId, ORDER_STATUS_OK, new Date());
            if (i > 0) {
                return Result.ok("确认收货成功！");
            }
        } else if (status.equals(ORDER_STATUS_WAITSEND)) {
            int i = ordersMapper.updateStatus(orderId, ORDER_STATUS_WAITRECEIVE, new Date());
            if (i > 0) {
                return Result.ok(ORDER_STATUS_SENDED);
            }
        }
        return Result.error(null);
    }

    /**
     * 根据token获取用户的地址信息
     *
     * @param token
     * @return
     */
    @Override
    public Result getUserAddress(String token) {
        Users users = usersController.getUserInfo(token);
        int userId = users.getUserId();
        //查询到所有该用户的地址信息
        List<Address> addressList = addressMapper.selectBatchById(userId);
        return Result.ok(addressList);
    }

    /**
     * 管理员获取所有用户的所有订单
     *
     * @return
     */
    @Override
    public Result queryAllOrders(Integer flag, String status, Integer pageCount, Integer pageSize) {
        Page<Orders> page = new Page<>(pageCount, pageSize);
        Page<Orders> ordersPage;
        //如果传入的状态是空
        if (status==null || status.isEmpty()) {
            if (flag==1) {
                //无条件分页查询所有订单
                ordersPage = ordersMapper.selectPage(page, null);
            }
            if (flag==2) {
                //表示查询宠物订单
                LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper
                        .ne(Orders::getGoodId,null);
                ordersPage = ordersMapper.selectPage(page, lambdaQueryWrapper);
            }
            if (flag==3) {
                //表示查询商品订单
                LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper
                        .ne(Orders::getProductId,null);
                ordersPage = ordersMapper.selectPage(page, lambdaQueryWrapper);
            }
        }else{
            if (flag==1) {
                //无条件分页查询所有订单
                LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(Orders::getStatus,status);
                ordersPage = ordersMapper.selectPage(page, lambdaQueryWrapper);
            }
            if (flag==2) {
                //表示查询宠物订单
                LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper
                        .ne(Orders::getGoodId,null)
                        .eq(Orders::getStatus,status);
                ordersPage = ordersMapper.selectPage(page, lambdaQueryWrapper);
            }
            if (flag==3) {
                //表示查询商品订单
                LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper
                        .ne(Orders::getProductId,null)
                        .eq(Orders::getStatus,status);
                ordersPage = ordersMapper.selectPage(page, lambdaQueryWrapper);
            }
        }


        return null;
    }

    /**
     * 根据订单id查询订单
     * 使用缓存空对象法解决缓存穿透、互斥锁法解决缓存击穿
     *
     * @param orderId
     * @return
     */
    @Override
    public Orders queryById(Integer orderId) {
        return getById(orderId);
    }

}




